//
//  WiiEditTaskViewController.m
//  iFeller
//
//  Created by Wii on 15/12/11.
//  Copyright © 2015年 Wii. All rights reserved.
//

#import "WiiTaskDetailViewController.h"
#import "WiiTaskDetailTableViewCell.h"
#import "WiiEditNotesViewController.h"
#import "WiiChoseRepeatViewController.h"
#import "XYChangeDateController.h"
#import "WiiAddTagsViewController.h"
#import "XYLocalPush.h"

#define Identifier @"EditTaskCELL"
#define CellHeight (60)
#define TheTaskNotes (4)
#define NumberOfSections (5)
#define NumberOfRows (1)
typedef NS_ENUM (NSInteger,WiiEditTaskCell){
    WiiEditTaskCellIcon = 0 ,
    WiiEditTaskCellTags ,
    WiiEditTaskCellDate ,
    WiiEditTaskCellRepeat ,
    WiiEditTaskCellNoet
};

typedef NS_ENUM (NSInteger,XYBarButton){
    XYBarButtonTime = 100,
    XYBarButtonList ,
    XYBarButtonOK ,
};
@interface WiiTaskDetailViewController () <UITableViewDelegate,UITableViewDataSource>
@property (nonatomic , strong) UIImageView *navBarBG;
@property (nonatomic , strong) UITableView *mainTableVIew;
@property (nonatomic , strong) XYSqlite3 *sql;

@property (nonatomic, assign) BOOL isSet;/*闹钟时间是否设定*/
@property (nonatomic, strong) NSString *SetTime;/*设定的时间*/
@property (nonatomic, strong) NSString *SetTable;/*设定的表*/
@end

@implementation WiiTaskDetailViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    //去除导航栏下方的横线
    self.navBarBG.hidden = YES;
    // 隐藏返回按钮
    [self.navigationItem setHidesBackButton:YES];
    
    [self.sql openDataBase];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navBarBG.hidden = NO;
    [self.sql closeTheDataBase];
}
- (void)viewDidLoad{
    [super viewDidLoad];
    self.navBarBG = [WiiKit findHairlineImageViewUnder:self.navigationController.navigationBar];

    [self initUserInterface];
    self.isSet = NO;
    switch (self.taskStatus) {
        case 0:
            self.SetTable = TableName_TheTaskAtHand;
            break;
        case 1:
            self.SetTable = TableName_MyTask;
            break;
        case 2:
            self.SetTable = TableName_FinishTask;
            break;
        default:
            break;
    }
    NSLog(@"%@", self.dataSource);
}

- (void)initUserInterface{
    
    UIButton *delButton = [UIButton buttonWithType:UIButtonTypeCustom];
    delButton.frame = CGRectMake(WiiZero, WiiZero, WiiButtonSize, WiiButtonSize);
    [delButton setBackgroundImage:[UIImage imageNamed:@"Del"] forState:UIControlStateNormal];
    [delButton addTarget:self action:@selector(delButtonHandleEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *delItem = [[UIBarButtonItem alloc]initWithCustomView:delButton];
    self.navigationItem.rightBarButtonItem = delItem;
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(WiiZero, WiiZero, WiiButtonSize, WiiButtonSize);
    [backButton setBackgroundImage:[UIImage imageNamed:@"BackArrow"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backItemHandleEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backItem;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.mainTableVIew];
}

#pragma mark - delButtonHandleEvent (删除按钮)
- (void)delButtonHandleEvent:(UIButton *)sender{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否删除?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAC = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.sql deleteTheDataBaseWithTableName:self.SetTable deleteName:self.dataSource[WiiTaskDataSourceWithName]];
        /*更新前页数据*/
        if (self.delegate) {
            [self.delegate backToReloadDatasource:self.taskStatus];
        }

        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction *cancelAC = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertVC addAction:confirmAC];
    [alertVC addAction:cancelAC];
    [self.view.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
 
}

- (void)backItemHandleEvent:(UIButton *)sender{
    /*推送*/
    if (self.isSet) {
        /*先删除*/
        [XYLocalPush cancelLocalNotification:self.SetTime];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss +zzz"];
        NSDate *dateString = [formatter dateFromString:self.SetTime];
        [XYLocalPush registerLocalNotification:dateString pushName:self.dataSource[WiiTaskDataSourceWithName] pushRepeat:self.dataSource[WiiTaskDataSourceWithRepeat]];
        /*增表*/
        [self.sql insertDataSourceToDBwithArray:self.dataSource tableName:TableName_TheTaskAtHand];
        /*删表*/
        [self.sql deleteTheDataBaseWithTableName:self.SetTable
                                      deleteName:self.dataSource[WiiTaskDataSourceWithName]];
    }
    
    /*更新前页数据*/
    if (self.delegate) {
        [self.delegate backToReloadDatasource:self.taskStatus];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([indexPath section] == WiiEditTaskCellNoet) {
        NSString *text = self.dataSource[TheTaskNotes];
        CGSize size = [text getSizeWithFont:[UIFont systemFontOfSize:15] forWidth:SCREEN_WIDTH - 74];
        if (size.height > CellHeight) {
            return size.height + 36;
        } else{
            return CellHeight;
        }
    } else {
        return CellHeight;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return NumberOfSections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return NumberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WiiTaskDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    cell.taskStatus = self.taskStatus;
    [cell getCellDataWithDataSource:self.dataSource IndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //presentViewController可能没在UI主线程中更新,需要触发一个操作，唤醒主线程（之前直接跳转出现卡顿或延迟）
    dispatch_async(dispatch_get_main_queue(), ^{
        switch ([indexPath section]) {
            case WiiEditTaskCellIcon:{
                WiiEditNotesViewController *notesVC = [[WiiEditNotesViewController alloc]init];
                notesVC.isTaskName = YES;
                [notesVC respondsButtonWithDoneEditNotes:^(NSString *text) { //bug1:
                    NSString *name = self.dataSource[WiiTaskDataSourceWithName];
                    [self.dataSource replaceObjectAtIndex:WiiTaskDataSourceWithName withObject:text];
                    [self.mainTableVIew reloadData];
                    
                    [self.sql updateDataBaseWithTableName:self.SetTable
                                               changeItem:@"name" changeContent:text changeName:name];
                }];
                notesVC.notesText = self.dataSource[indexPath.section];
                [self presentViewController:notesVC animated:YES completion:nil];
            }
                break;
            case WiiEditTaskCellTags:{
                WiiAddTagsViewController *addTagsVC = [[WiiAddTagsViewController alloc]init];
                addTagsVC.beforeTags = self.dataSource[WiiTaskDataSourceWithTags];
                [addTagsVC respondsButtonWithRepeat:^(NSString *tags) {
                [self.dataSource replaceObjectAtIndex:WiiTaskDataSourceWithTags withObject:tags];
                [self.mainTableVIew reloadData];
                [self.sql updateDataBaseWithTableName:self.SetTable changeItem:@"tags" changeContent:self.dataSource[WiiTaskDataSourceWithTags] changeName:self.dataSource[WiiTaskDataSourceWithName]];
                }];
                [self presentViewController:addTagsVC animated:YES completion:nil];
            }
                break;
            case WiiEditTaskCellDate:{
                XYChangeDateController *dateVC = [[XYChangeDateController alloc]init];
                dateVC.CalenderStatus = 1;
                [dateVC respondsButtonWithDoneEditNotes:^(NSString *text) {
                    self.SetTime = text;
                    [self.dataSource replaceObjectAtIndex:WiiTaskDataSourceWithFinish withObject:text];
                    [self.mainTableVIew reloadData];
                    [self.sql updateDataBaseWithTableName:self.SetTable changeItem:@"finishDate" changeContent:text changeName:self.dataSource[WiiTaskDataSourceWithName]];
                    self.isSet = YES;
                }];
                [self presentViewController:dateVC animated:YES completion:nil];
            }
                break;
            case WiiEditTaskCellRepeat:{
                WiiChoseRepeatViewController *choseRepeatVC = [[WiiChoseRepeatViewController alloc]init];
                [choseRepeatVC respondsButtonWithRepeat:^(NSString *text) {
                    [self.dataSource replaceObjectAtIndex:WiiTaskDataSourceWithRepeat withObject:text];
                    [self.mainTableVIew reloadData];
                    NSLog(@"%@", self.dataSource[WiiTaskDataSourceWithRepeat]);
                    [self.sql updateDataBaseWithTableName:self.SetTable changeItem:@"repeat" changeContent:self.dataSource[WiiTaskDataSourceWithRepeat] changeName:self.dataSource[WiiTaskDataSourceWithName]];
                }];
                [self presentViewController:choseRepeatVC animated:YES completion:nil];
            }
                break;
            case WiiEditTaskCellNoet:{
                WiiEditNotesViewController *notesVC = [[WiiEditNotesViewController alloc]init];
                [notesVC respondsButtonWithDoneEditNotes:^(NSString *text) {
                    [self.dataSource replaceObjectAtIndex:WiiTaskDataSourceWithNotes withObject:text];
                    [self.mainTableVIew reloadData];
                    [self.sql updateDataBaseWithTableName:self.SetTable changeItem:@"notes" changeContent:self.dataSource[WiiTaskDataSourceWithNotes] changeName:self.dataSource[WiiTaskDataSourceWithName]];
                }];
                notesVC.notesText = self.dataSource[indexPath.section];
                [self presentViewController:notesVC animated:YES completion:nil];
            }
                break;
            default:
                break;
        }
    });
}
#pragma mark - setter/getter

- (UITableView *)mainTableVIew{
    if (!_mainTableVIew) {
        _mainTableVIew = [[UITableView alloc]initWithFrame:self.view.bounds];
        _mainTableVIew.delegate = self;
        _mainTableVIew.dataSource = self;
        [_mainTableVIew registerNib:[UINib nibWithNibName:@"WiiTaskDetailTableViewCell" bundle:nil] forCellReuseIdentifier:Identifier];
        _mainTableVIew.separatorStyle = NO;
    }
    return _mainTableVIew;
}

- (XYSqlite3 *)sql{
    if (!_sql) {
        _sql = [[XYSqlite3 alloc]init];
    }
    return _sql;
}

@end
